<?php defined('SYSPATH') or die('No direct script access.');

/**
 * @file provinceandcity.php
 * @brief 
 * @author Lionel Tsai
 * @version 1.0
 * @date 2012-08-02
 */


define('PROVINCECITY_CUSGET', 0);
class Model_Provinceandcity extends ORM {

	protected $_table_name = 'terms';
	protected $_primary_key = 'term_id';
	protected $_has_many = array(
		'types' => array('model' => 'type', 'foreign_key' => 'term_id')
	);


	function as_array($type = PROVINCECITY_CUSGET) {
	 $ret = array();
	 switch($type) {
	 case PROVINCECITY_CUSGET:
		//$ret = parent::as_array();
		$ret['province_id'] = $this->term_id;
		$ret['province_name'] = $this->name;

		$pinyin = new Tool_Pinyinparse();
		$ret['province_slug'] = $pinyin->Pinyin($this->name, 'UTF-8');
		
		$province_id = $ret['province_id'];
		$term = ORM::factory('city');
	

		$order =  'asc';
		$type = ORM::factory('type');
		$types = $type->where('parent', '=', $province_id)->find_all();

		$total_count =  $type->where('parent', '=', $province_id)->count_all();
		$cityids = array();
		foreach($types as $typ) {
			array_push($cityids, $typ->term_id);
		}
		//var_dump($cityids);
		$term
			 ->and_where('term_id', 'IN',$cityids )
			 ->order_by(DB::expr("CONVERT(name USING GBK )"),$order);
			
			
		$terms = $term
					->where('term_id', '>', 54)
					->and_where('term_id', '<', 417)
					->find_all();
		$ret['cities'] = array();

		foreach($terms as $tem)
		{
			$ret['cities'][] = $tem->as_array(PROVINCECITY_CUSGET);
		}

		break;
	 default:
		$ret = parent::as_array();
		//get pinyin
		$pinyin = new Tool_Pinyinparse();
	    $ret['term_pinyin'] = $pinyin->Pinyin($this->name, 'UTF-8');
		break;	
	 }
	 return $ret;
	}
}
